package com.wenx.thread;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 两个线程交替打印
 */
public class ThreadMain3 {

    Lock reentrantLock = new ReentrantLock();
    Condition condition1 = reentrantLock.newCondition();
    Condition condition2 = reentrantLock.newCondition();

    static Thread thread1 = null;
    static Thread thread2 = null;

    volatile boolean temp = true;

    public static void main(String[] args) {

        ThreadMain3 threadMain3 = new ThreadMain3();
        thread1 = new Thread(threadMain3::printNum, "线程1");
        thread2 = new Thread(threadMain3::printStr, "线程2");

        thread1.start();
        thread2.start();

        //TimeUnit.SECONDS.sleep(10L);

    }

    private void printNum() {
        List<Integer> collect = Stream.of(1, 2, 3, 4, 5, 6, 7, 8)
                .collect(Collectors.toList());
        try {
            reentrantLock.lock();
            for (Integer integer : collect) {
                try {
                    while (!temp)
                        condition1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print(integer + " ");
                temp = false;
                condition2.signal();
            }
        } finally {
            reentrantLock.unlock();
        }
    }

    private void printStr() {
        List<String> collect = Stream.of("a", "b", "c", "d", "e", "f", "g", "h")
                .collect(Collectors.toList());
        try {
            reentrantLock.lock();
            for (String str : collect) {
                try {
                    while (temp)
                        condition2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.print(str + " ");
                temp = true;
                condition1.signal();
            }
        } finally {
            reentrantLock.unlock();
        }
    }

}
